<template>
    <rx-dialog @ok="handleCompleteCheck" @cancel="closeWindow" :okText="i18n('taskCheck.btnAssign','提交')"
               :btnAlign="'center'">
        <template #leftToolbar>
            <a-button @click="temporaryOpinion">{{ i18n('taskCheck.btnProvisional', '暂存意见') }}</a-button>
        </template>
        <rx-fit>
            <template #middle>
                <div style="width:100%;padding:10px;">
                    <div class="opinion-common">
                        <div class="opinion">
                            <div :class="{'task-opinion':opinionRequired}">{{ i18n('taskCheck.opinion', '意见') }}:
                                <a-radio-group v-if="showOpinion()" v-model:value="checkType" @change="checkTypeChange">
                                    <a-radio :value="item.value" :key="item.value" v-for="item in checkTypes">
                                        {{ $i18(item.text) }}
                                    </a-radio>
                                </a-radio-group>
                            </div>
                            <div @click.stop="opinionShow=!opinionShow">
                                <my-icon type="iconxinzeng"></my-icon>
                                {{ i18n('taskCheck.insertOpinion', '插入常用意见') }}
                            </div>
                        </div>
                        <!--插入意见弹窗 -->
                        <div class="opinion-parenthesis" id="opinionShow" v-show="opinionShow">
                            <div class="opinion-parenthesis-triangle"></div>
                            <div style="position: relative">
                                <ul class="opinion-parenthesis-list">
                                    <li v-for="item in commonOpinions" :value="item.opText" :label="item.opText">
                                        <my-icon type="iconoffline" @click.stop="closeOpinion(item)"></my-icon>
                                        <div @click="handleChange(item.opText)">{{ item.opText }}</div>
                                    </li>
                                </ul>
                                <div class="opinion-parenthesis-add" @click.stop="addOpinionShow =!addOpinionShow">
                                    <my-icon type="iconxinzeng" style="margin-right: 4px;"></my-icon>
                                    {{ i18n('taskCheck.newOpinion', '新建常用意见') }}
                                </div>
                                <!--新建常用意见弹窗-->
                                <div class="opinion-common-add" v-show="addOpinionShow">
                                    <div style="position: relative">
                                        <div class="opinion-common-add-triangle"></div>
                                        <div style="margin: 15px 15px 0px 15px;">
                                            {{ i18n('taskCheck.commonOpinion', '常用意见') }}
                                        </div>
                                        <a-textarea :placeholder="i18n('taskCheck.commonOpinionDesc','请输入意见作为常用意见')"
                                                    v-model:value="addOpinion"
                                                    style="height:60px;margin:15px;width: 309px;"></a-textarea>
                                        <div class="opinion-common-add-button">
                                            <a-button @click="addOpinionShow = false">
                                                {{ $ti18('rxForm.cancelBtn', '取消') }}
                                            </a-button>
                                            <a-button @click="saveOpinion" type="primary">
                                                {{ $ti18('rxForm.saveBtn', '保存') }}
                                            </a-button>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <rx-tribute ref="rxtribute" style="height:100px;margin-top: 10px"></rx-tribute>
                    </div>

                    <div class="bpm-more-common-executors" v-show="canShowNextTask()">
                        <bpm-task-executors style="flex: 1" ref="taskExecutors" :nodeExecutors="nodeExecutors"
                                            :task-config="taskConfig"
                                            :processConfig="parentVm().processConfig">

                        </bpm-task-executors>
                    </div>
                    <!--  更多收起  -->
                    <div class="bpm-more-common" v-show="showMoreOptions">
                        <a-collapse v-model:activeKey="activeKeys">
                            <a-collapse-panel key="1" :header="i18n('taskCheck.moreOptions','更多选项')">
                                <a-form ref="form">
                                    <a-form-item :label="i18n('taskCheck.attachment','附件')">
                                        <rx-attach-component v-model="fileList" class="uploader-btn-ctl"></rx-attach-component>
                                    </a-form-item>
                                    <a-form-item :label="i18n('taskCheck.cc','抄送')" style="width: 100%;">
                                        <rx-user-component v-model="copyUsers" :isAccount="false"
                                                           :single="false" style="width: 100%;"></rx-user-component>
                                    </a-form-item>
                                    <a-form-item :label="i18n('taskCheck.assoProcess','关联流程')" style="width: 100%;">
                                        <rx-text-list
                                            v-model="relInsts"
                                            :showclose="true"
                                            :readonly="false"
                                            valuefield="id" textfield="name"
                                            @click="selectBpmInst()"
                                            style="width: 100%;"
                                        >
                                            <EllipsisOutlined/>
                                        </rx-text-list>
                                    </a-form-item>
                                </a-form>
                            </a-collapse-panel>
                        </a-collapse>
                    </div>
                </div>
            </template>
        </rx-fit>
    </rx-dialog>
</template>
<script>
import {RxDialog, Util, RxFit, RxTextList} from '@lowcode/jpaas-base-lib';
import {RxUserComponent, RxAttachComponent} from '@lowcode/jpaas-share-component';
import BpmtaskApi from '@/common/api/bpm/bpmTask'
import BpmOpinionLibApi from "@/common/api/bpm/bpmOpinionLib";
import BpmTaskExecutors from "../../components/BpmTaskExecutors.vue";
import BpmMyEvents from "../../components/dialog/BpmMyEvents.vue";
import RxTribute from "../../tribute/rx-tribute.vue";

export default {
    name: 'bpm-task-check',
    components: {
        RxUserComponent,
        BpmTaskExecutors,
        RxAttachComponent,
        RxFit,
        RxDialog,
        BpmMyEvents,
        RxTextList,
        RxTribute
    },
    props: {
        layerid: String,
        parentVm: Function,
        destroy: Function,
        taskId: {
            type: String,
            required: true
        },
        /**
         * 表单JSON
         */
        formJson: String,
        systemHand: Boolean,
        /**
         * 表单中可以填写的意见名称
         */
        opinionName: "",
        /**
         * 任务配置JSON
         */
        taskConfig: {
            type: Object
        },
        //显示更多选项。
        showMoreOptions: {
            type: Boolean,
            default: true
        },
        //幂等号
        idempotenceid:{
            type:String
        }
    },
    data() {
        return {
            labelCol: {span: 3},
            wrapperCol: {span: 9},

            checkType: 'AGREE',
            copyUsers: [],
            opinion: "",

            commonOpinions: [],
            fileList: [],
            temporaryOpinionObj: {},
            relInsts: [],
            advanced: true,
            checkTypes: [{text: this.i18n('taskCheck.pass', '通过'), value: "AGREE"},
                {text: this.i18n('taskCheck.noPass', '不通过'), value: "REFUSE"}],
            opinionShow: false,
            addOpinionShow: false,
            addOpinion: '',
            activeKeys: '0',
            //执行人
            nodeExecutors: [],
        }
    },
    computed: {
        opinionRequired() {
            if (!this.taskConfig.switchOptions) {
                return false;
            }
            return this.taskConfig.switchOptions.includes("opinionRequired");
        }
    },
    created() {
        this.getTemporaryOpinion();

        this.getCommonUserOpinions();

        //初始化用户数据。
        this.initUser();
        // 初始化意见
        this.initCheckTypes();
    },
    methods: {
        i18n(name, text, key) {
            return this.$ti18(name, text, "bpmTask", key);
        },
        initUser() {
            BpmtaskApi.getTaskFlowNodesExecutors(this.taskId, 'AGREE', JSON.parse(this.formJson), this.systemHand).then(res => {
                this.nodeExecutors = res;
            })
        },
        checkTypeChange(e) {
            BpmtaskApi.getTaskFlowNodesExecutors(this.taskId, e.target.value, JSON.parse(this.formJson), this.systemHand).then(res => {
                this.nodeExecutors = res;
            })
        },
        //显示高级选择项
        toggleAdvanced() {
            this.advanced = !this.advanced;
        },
        handleCompleteCheck(e) {
            let self = this;
            var ctl = this.$refs.taskExecutors;
            var rxtribute = this.$refs.rxtribute;
            //抄送用户
            let copyUserUserIds = this.getCopyUserAccounts();

            let nodeUserMap = ctl.getNodeUserMap();
            let destNodeId = ctl.getDestNodeId();
            let cmd = {
                taskId: self.taskId,
                checkType: self.checkType,
                opinion: rxtribute.getOpinion(),

                copyUserUserIds: copyUserUserIds,
                linkupAccounts: rxtribute.getLinkup(),
                nodeExecutors: nodeUserMap,
                formJson: self.formJson,
                systemHand: self.systemHand,
                opinionName: self.opinionName,
                opFiles: JSON.stringify(self.fileList),
                relInsts: JSON.stringify(self.relInsts)
            }
            //设置目标节点。
            if (destNodeId) {
                cmd.destNodeId = destNodeId;
            }
            //幂等号
            if (self.idempotenceid) {
                cmd.idempotenceid = self.idempotenceid;
            }

            //配置意见必填。
            if (this.taskConfig.switchOptions.includes("opinionRequired")) {
                if (!rxtribute.getOpinion()) {
                    let message = this.i18n('form.tipOpinion', '请填写审批意见!')
                    this.$message.warn(message);
                    e.loading = false;
                    return;
                }
            }
            BpmtaskApi.checkComplete(cmd).then(resp => {
                e.loading = false;
                if (resp.data && resp.data.async) {
                    Util.closeWindow(self, 'async');
                } else if (resp.success) {
                    Util.closeWindow(self, 'ok');
                }
            })

        },

        /**
         * 获取抄送用户。
         * @returns {string}
         */
        getCopyUserAccounts() {
            var accounts = [];
            if (this.copyUsers && this.copyUsers.length > 0) {
                this.copyUsers.forEach(item => {
                    accounts.push(item.id);
                })
            }
            return accounts.join(",");
        },
        closeWindow() {
            Util.closeWindow(this, 'cancel')
        },
        saveOpinion() {
            var self = this;
            if (!this.addOpinion) {
                this.$message.warning(self.i18n('taskCheck.sureToClear', '请填写需要保存的常用意见!'));
                return;
            }
            BpmOpinionLibApi.save({opText: this.addOpinion}).then(res => {
                if (res.success) {
                    this.getCommonUserOpinions();
                    this.addOpinion = "";
                    this.addOpinionShow = false

                }
            });
        },
        closeOpinion(opinion) {
            let self_ = this;
            this.$confirm({
                title: this.$ti18('rxMsa.actionTips', '操作提示'),
                zIndex: 9999,
                content: self_.i18n('taskCheck.sureToClear', '确定要删除此条意见吗？'),
                okText: this.$ti18('rxForm.ackBtn', '确认'),
                cancelText: this.$ti18('rxForm.cancelBtn', '取消'),
                onOk() {
                    BpmOpinionLibApi.del({ids: opinion.opId}).then(res => {
                        self_.getCommonUserOpinions();
                    })
                },
                onCancel() {
                }
            })
        },
        getCommonUserOpinions() {
            BpmOpinionLibApi.getUserText().then(res => {
                this.commonOpinions = res;
            })
        },
        handleChange(value) {
            this.opinion += value;
            this.opinionShow = false;
            this.$refs.rxtribute.setTributeText(value);
        },

        //暂存意见
        temporaryOpinion() {
            var id = this.temporaryOpinionObj.id ? this.temporaryOpinionObj.id : "";
            let opinion = this.$refs.rxtribute.getOpinion();
            if (this.taskId) {
                if (opinion) {
                    BpmtaskApi.temporaryOpinion(this.taskId, opinion, id).then(res => {
                        Util.closeWindow(this, 'ok');
                    });
                } else {
                    this.$message.warning(this.i18n('taskCheck.noNullOpin', "意见不能为空"));
                    return
                }
            }
        },
        //获取暂存意见
        getTemporaryOpinion() {
            if (this.taskId) {
                BpmtaskApi.getTemporaryOpinion(this.taskId).then(res => {
                    if (res) {
                        this.opinion = res.opinion;
                        this.$refs.rxtribute.setTributeText(this.opinion);
                        this.temporaryOpinionObj = res;
                    }
                });
            }
        },
        selectBpmInst() {
            var conf = {
                component: BpmMyEvents,
                title: this.i18n('taskCheck.assoProcess', '关联流程'),
                curVm: this, widthHeight: ['1024px', '600px']
            };
            var self_ = this;
            Util.open(conf, function (action, relInsts) {
                if (action != 'ok') return;

                var idAry = [];
                for (var i = 0; i < self_.relInsts.length; i++) {
                    var o = self_.relInsts[i];
                    idAry.push(o.id);
                }

                for (var i = 0; i < relInsts.length; i++) {
                    var o = relInsts[i];
                    if (idAry.includes(o.id)) {
                        continue;
                    }
                    self_.relInsts.push(o);
                }
            });
        },

        opinionChange(e) {
            if (this.opinion && this.opinion.length > 500) {
                this.opinion = this.opinion.substring(0, 500)
                this.$message.warning(this.i18n('taskCheck.opinionSize', '意见限500字!'));
            }
        },
        initCheckTypes() {
            if (this.taskConfig.multipleType != 'normal' && this.taskConfig.signConfig.options) {
                this.checkTypes = this.taskConfig.signConfig.options;
            }
            if (this.taskConfig.multipleType == 'normal' && this.taskConfig.showOpinion) {
                this.checkTypes = this.taskConfig.options;
            }
        },
        showOpinion() {
            //普通任务节点
            if (this.taskConfig.multipleType == 'normal' && this.taskConfig.showOpinion
                && this.taskConfig.options && this.taskConfig.options.length > 0) {
                return true;
            }
            if (this.taskConfig.multipleType != 'normal' && this.taskConfig.signConfig.options) {
                return true;
            }
            return false;
        },
        //是否显示下一步执行人。
        canShowNextTask() {
            return !this.taskConfig.switchOptions.includes("shieldExecutePath");
        }
    }
}
</script>
<style scoped>
.uploader-btn-ctl ::v-deep(.uploader-btn){
    padding: 5px 6px;
}
.bpm-more-common-executors {
    display: flex;
    align-items: center;
    margin-top: 20px;
}

.bpm-more-common-executors-next {
    margin-right: 10px;
}

.bpm-more-common {
    margin-top: 20px;
}

.bpm-more-common >>> .ant-collapse-header {
    background-color: white !important;
}

.opinion-common-add-button {
    border-top: solid 1px #d9d9d9;
    text-align: right;
}

.opinion-common-add-button button {
    margin-right: 15px;
    margin-top: 5px;
}

.opinion-parenthesis-triangle {
    height: 5px;
    width: 0px;
    border: 10px solid;
    border-color: transparent transparent white transparent;
    position: absolute;
    top: -17px;
    right: 36px;
}

.opinion-common-add-triangle {
    height: 5px;
    width: 0px;
    border: 10px solid;
    border-color: transparent transparent white transparent;
    position: absolute;
    top: -35px;
    left: 57px;
}

.opinion-common-add {
    position: absolute;
    bottom: -185px;
    left: 0px;
    width: 337px;
    height: 170px;
    background-color: #ffffff;
    box-shadow: 0px 0px 13px 0px rgba(6, 0, 1, 0.17);
    border: solid 1px #eeeeee;
    border-radius: 4px;
    z-index: 9999;
    box-sizing: border-box;
}

.opinion-parenthesis-add {
    border-top: solid 1px #d9d9d9;
    height: 35px;
    line-height: 35px;
    padding-left: 12px;
    cursor: pointer;
    color: #444444;
    display: flex;
    align-items: center;
}

.opinion-parenthesis-add i {
    font-size: 18px;
    margin-right: 5px;
}

.opinion-parenthesis-list {
    margin-top: 5px;
}

.opinion-parenthesis-list li {
    color: #444444;
    display: flex;
    justify-content: center;
    align-items: center;
    padding: 0px 12px;
    height: 30px;
    line-height: 30px;
    cursor: pointer;
}

.opinion-parenthesis-list li i {
    margin-right: 5px;
    font-size: 18px;
}

.opinion-parenthesis-list li i:hover {
    color: #4285f4
}

.opinion-parenthesis-list li div {
    flex: 1;
    overflow: hidden;
    text-overflow: ellipsis;
    display: -webkit-box;
    -webkit-line-clamp: 1;
    -webkit-box-orient: vertical;
    padding-left: 5px;
}

.opinion-parenthesis-list li div:hover {
    background-color: #f2f3f6;
    border-radius: 4px;
}

.opinion {
    display: flex;
    color: #444444;
    font-size: 14px;
    padding-bottom: 6px;
}

.opinion .ant-radio-group {
    margin-left: 10px;
}

.opinion div:nth-child(1) {
    flex: 1;
    color: #303030;
}

.opinion div:nth-child(2) {
    display: flex;
    justify-content: center;
    align-items: center;
    cursor: pointer;
}

.opinion div:nth-child(2) i {
    margin-right: 5px;
    font-size: 17px;
}

.opinion-common {
    position: relative;
}

.opinion-parenthesis {
    position: absolute;
    top: 28px;
    right: 0px;
    width: 337px;
    background-color: #ffffff;
    box-shadow: 0px 0px 13px 0px rgba(6, 0, 1, 0.17);
    border: solid 1px #eeeeee;
    border-radius: 4px;
    z-index: 9999;
}

.task-opinion::before {
    content: "*";
    color: red;
    margin-right: 5px;
}
</style>
